// Package server
// @Author: zhangdi
// @File: main
// @Version: 1.0.0
// @Date: 2023/8/24 15:25
package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"path"
	"path/filepath"
	"server/application/constant/keys"
	dbinstance "server/application/db/dbinit"
	"server/application/db/schema/tables"
	"server/application/first"
	"server/application/router"
	"server/pkg/configs"
	"server/pkg/mylog"
	"server/pkg/utils"
	"server/setting"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {

	r := gin.Default()
	// 设置模板路径
	r.LoadHTMLFiles("templates/index/index.html")
	//我们注册了 "/static" 路径，并指定其对应的静态文件目录为 "./static"
	r.Static("/static", "./static")
	//我们注册了 "/assets" 路径，并指定其对应的静态文件目录为 "/templates/index/assets"
	r.Static("/assets", "./static/assets")

	//web 日志
	setupLogger()

	//router.Use(requestLogger())

	// 定义渲染模板的路由处理函数
	router.Register(r)

	//初始化配置文件和mysql
	var yamlFlag string
	flag.StringVar(&yamlFlag, "yaml", "", "YAML parameter")
	flag.Parse()
	yamlPath := filepath.Join("configs.yaml")
	if yamlFlag != "" {
		//传参 server -yaml 021
		yamlPath = filepath.Join("companies", yamlFlag+".yaml")
	}
	fmt.Println("yamlPath:", yamlPath)

	confPath := filepath.Join(yamlPath)

	configs.InitConfig(confPath)

	first.SetFirstConfigValue() //写入初始配置值到config

	dbinstance.InitDb() //初始化mysql

	tables.InitDbInstance(dbinstance.GetDbInstance(), dbinstance.GetDbInstance())

	first.InitProgram() //初始化任务、字典、菜单

	mylog.SetLogPath(path.Join(utils.GetUserHomeDir(), "id_serve", "logs"))
	port := configs.GetConf().GetString(keys.ConfigKeyGinPort)
	if port == "" {
		port = setting.GinPort
	}
	err := r.Run(":" + port)

	if err != nil {
		panic(err)
	}

}

func setupLogger() {
	// 创建日志文件目录
	logDir := "./log/"
	err := os.MkdirAll(logDir, os.ModePerm)
	if err != nil {
		log.Fatalf("Failed to create log directory: %v", err)
	}

	// 设置日志文件名为当前日期
	logFile := logDir + time.Now().Format("2006-01-02") + ".log"

	// 创建日志文件，追加模式写入
	f, _ := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

	// 设置日志输出到文件
	gin.DefaultWriter = io.MultiWriter(f)
	log.SetOutput(io.MultiWriter(f, os.Stdout))
}
